<template>
  <div class="chat-container" style="height: 750px">
    <!-- Left side: User list -->
    <div class="left-side">
      <!-- Search input (moved outside) -->
      <div class="search-wrapper">
        <el-input v-model="searchUserName" placeholder="回车搜索用户" class="search-input" @keydown.enter.native="searchUserForForm"></el-input>
      </div>
      <!-- User list (with scroll) -->
      <el-scrollbar class="user-list-scroll">
        <el-row>
          <el-col :span="24" v-for="form in messageForm" :key="form.sendUser.userId" @click.native="chooseUser(form.sendUser)" class="user-item" v-if="messageForm.length !== 0">
            <div class="user-avatar-wrapper">
              <div :class="{ 'online-dot': form.isOnline }"></div>
              <!-- Element UI Badge for showing unread messages -->
              <el-badge :value="form.noReadMessageLength" class="message-badge" v-if="form.noReadMessageLength > 0">
                <img src="http://localhost/dev-api/profile/avatar/2024/06/25/7e8187f2cd43662b_big_20240625191708A001.png" class="user-avatar">
              </el-badge>
              <img src="http://localhost/dev-api/profile/avatar/2024/06/25/7e8187f2cd43662b_big_20240625191708A001.png" class="user-avatar" v-else>
            </div>
            <div class="user-details">
              <div class="user-name">{{ form.sendUser.userName }}</div>
              <div class="user-last-message">{{ form.lastMessage }}&nbsp;</div>
            </div>
          </el-col>
        </el-row>
      </el-scrollbar>
    </div>
    <!-- Right side: Chat box -->
    <div class="right-side">
      <!-- Chat header -->
      <div class="chat-header">
        <span v-if="currentUser">{{ currentUser.userName }}</span>
      </div>
      <!-- Chat messages -->
      <el-scrollbar class="chat-messages" ref="messageContainer">
        <div class="messageBox" v-for="message in messages" :key="message.handle" :class="{ ownMessage: message.sendUser == loginUser.id, otherMessage: message.sendUser != loginUser.id }">
          <div><img :src="message.sendUser == loginUser.id ? loginUser.avatar : 'http://localhost/dev-api/profile/avatar/2024/06/25/7e8187f2cd43662b_big_20240625191708A001.png'" alt="" style="border: 1px solid #70c1fa;"></div>
          <div class="messageContent">{{ message.content }}</div>
          <div class="messageTime">{{ message.createTime }}</div>
        </div>
      </el-scrollbar>
      <div class="chat-input">
        <el-input v-model="newMessage.content" placeholder="请输入聊天内容" autosize class="message-input" @keydown.enter.native="sendMessage"></el-input>
        <el-button type="primary" @click.native="sendMessage" class="send-button">发送</el-button>
      </div>
    </div>
  </div>
</template>

<script>
  // 获取用户信息和聊天信息后端接口，根据自己的实际项目修改
  import {findMessageBySendUserAndReceiveUser, searchUserForForm} from '@/api/callback/communication.js'
  // 发送信息给指定userId的websocket
  import {sendMessage} from '@/api/callback/communication.js'
  // 根据botQuest获取对话信息
  import { botQuest } from '@/api/callback/communication.js'
  // 刚刚写的websocket
  import websocket from '@/utils/websocket.js'

  export default {
    data () {
      return {
        currentUser: null, // 当前聊天的人
        loginUser: null,
        messages: [],
        messageForm: [], // 聊天所有信息
        newMessage: {
          handle: '',
          sendUser: '',
          receiveUser: '',
          content: '',
          is_read: '0',
          createTime: ''
        },
        searchUserName: '客服1'
      }
    },
    methods: {
      async fetchMessages (userId) {
        if (!userId) {
          this.searchUserForForm()
          return
        }
        if (this.loginUser.id == null) {
          this.$message.error('登录用户编号获取失败,请重新登录!')
          return
        }
        findMessageBySendUserAndReceiveUser(userId, this.loginUser.id ).then(async res => {
          await this.searchUserForForm()
          console.log(res)
          this.messages = res.data
          // 将聊天记录总下拉到最下方
          this.$nextTick(() => {
            this.scrollToBottom()
          })
        })
      },

   formatCurrentDate() {
    const now = new Date();

    // 获取年、月、日、小时、分钟、秒、毫秒
    const year = now.getFullYear();
    const month = this.padZero(now.getMonth() + 1); // 月份是从0开始的，所以要加1
    const day = this.padZero(now.getDate());
    const hours = this.padZero(now.getHours());
    const minutes = this.padZero(now.getMinutes());
    const seconds = this.padZero(now.getSeconds());
    const milliseconds = this.padZero(now.getMilliseconds(), 3); // 保证毫秒是3位数

    // 拼接成所需格式
    const formattedDate = `${year}-${month}-${day}T${hours}:${minutes}:${seconds}.${milliseconds}${this.getTimezoneOffset(now)}`;

    return formattedDate;
  },

  // 补零函数，确保单个数字是两位数或者三位数
  padZero(num, length = 2) {
    return ('00' + num).slice(-length);
  },

  // 获取时区偏移量，格式为 ±HH:mm
  getTimezoneOffset(date) {
    const offsetMinutes = date.getTimezoneOffset();
    const offsetHours = this.padZero(Math.abs(Math.floor(offsetMinutes / 60)));
    const offsetMinutesString = this.padZero(Math.abs(offsetMinutes % 60));
    const offsetSign = offsetMinutes <= 0 ? '+' : '-'; // getTimezoneOffset 返回正数表示本地时间比 UTC 时间早，负数表示本地时间比 UTC 时间晚
    return `${offsetSign}${offsetHours}:${offsetMinutesString}`;
  },
      sendMessage () {
        if (!this.newMessage.content.trim()) {
          this.$message.warning('请输入聊天内容')
          return
        }
        this.newMessage.content = this.newMessage.content.trim()
        if (this.loginUser.id == null) {
          this.$message.error('登录用户编号获取失败,请重新登录!')
          return
        }
        if (this.loginUser.id  === this.currentUser.userId) {
          this.$message.error('不能给自己发送信息!')
          return
        }

        this.newMessage.sendUser = this.loginUser.id
        this.newMessage.receiveUser = this.currentUser.userId

        if(this.currentUser.userId === 'bot'){
          botQuest(this.newMessage.content).then(res => {
            if (res.code !== 200) {
              this.$message.error(res.message)
              return
            }
            res.data.receiveUser = this.loginUser.id
            this.newMessage.createTime = this.formatCurrentDate();
            this.newMessage.handle = Math.random().toString(36).slice(-6);
            this.newMessage.remark = null;
            this.newMessage.updateBy = null
            this.newMessage.updateTime = null;
            this.newMessage.createBy = null;
            this.newMessage.isRead = "0";
            res.data.is_read = "0";
            let obj = Object.assign({}, this.newMessage);
            this.messages = this.messages.concat(obj, res.data)
          })
          return
        }

        this.sendWebSocketMessage(this.newMessage)
        sendMessage(this.newMessage).then(res => {
          if (res.code !== 200) {
            this.$message.error(res.message)
            return
          }
          this.chooseUser(this.currentUser)
        })
      },
      // 消息过多的时候滚动到最新消息位置
      scrollToBottom () {
        // 使用 $refs 来获取对消息容器的引用
        const container = this.$refs.messageContainer.$refs.wrap
        // 滚动到底部
        container.scrollTop = container.scrollHeight
      },
      checkAvatar (avatar) {
        if (avatar) {
          return avatar
        }
        return ''
      },
      chooseUser (user) {
        this.currentUser = user
        if(user.userId==="bot") {
          this.messages = []
          // 将聊天记录总下拉到最下方
          this.$nextTick(() => {
            this.scrollToBottom()
          })
          return
        }
        this.messages = []
        this.fetchMessages(user.userId)
        this.connectWebSocket(this.loginUser.id)
      },
      // 初始化websocket
      async connectWebSocket (userId) {
        await new Promise((resolve) => {
          websocket.Init(userId)

          // 在 WebSocket 连接成功时调用 resolve
          websocket.getWebSocket().onopen = () => {
            console.log('WebSocket连接成功')
            resolve()
          }
        })
      },
      // 发送信息
      sendWebSocketMessage (message) {
        websocket.getWebSocket().onmessage = (event) => {
          // 处理消息，这里你可以根据实际需求更新页面上的数据
          console.log('收到的消息WebSocket2:', event)
          // 更新收到的消息
          // receivedMessage.value = event.data
          if (this.currentUser) {
            this.fetchMessages(this.currentUser.userId)
          } else {
            this.fetchMessages()
          }
        }
      },
      handleMessage (message) {
        // 内容进行相应的处理
        const parsedMessage = JSON.parse(message)
        console.log('收到信息:', parsedMessage)
        if (this.currentUser) {
          this.fetchMessages(this.currentUser.userId)
        } else {
          this.fetchMessages()
        }
      },
      // 获取所有信息
      searchUserForForm () {
        if (this.loginUser !== null) {
          searchUserForForm(this.loginUser.id, this.searchUserName).then(res => {
            if (res.code !== 200) {
              this.$message.error(res.message)
              return
            }
            this.messageForm = res.data
            let bot = {
              sendUser:{
                userId: 'bot',
                userName:'bot',
                avatar: ""
              },
              isOnline:"true",
              messages:"",
              noReadMessageLength: 0,
              receiveUser:{
                userId: this.loginUser.id,
                userName:this.loginUser.userName,
                avatar: this.loginUser.avatar
              },
              lastMessage: '欢迎使用机器人客服'
            }
            this.messageForm = this.messageForm.concat(bot)
          })
        }
      },
    },
    mounted () {
      websocket.setMessageCallback((res) => {
        this.handleMessage(res)
      })
    },
    created () {
      this.loginUser= this.$store.state.user
      this.searchUserForForm()
      // 获取登录用户userId,请根据自己实际项目获取
      this.connectWebSocket(this.loginUser.id)
      // if (userId) {
      //   getUser(userId).then(res => {
      //     if (res.code === 200) {
      //       if (res.data) {
      //         this.loginUser = res.data
      //       } else {
      //         this.loginUser.id = userId
      //       }
      //     }
      //   }).then(() => {
      //
      //   })
      // }
    }
  }
</script>


<style scoped>
  .chat-container {
    display: flex;
    height: 100%;
    background: linear-gradient(to bottom right, #FFFFFF, #ECEFF1);
  }

  .left-side {
    position: relative; /* Position relative for absolute positioning */
    flex: 1;
    padding: 20px;
    border-right: 1px solid #eaeaea;
    border-radius: 10px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
  }

  .search-input {
    position: absolute;
    top: 20px;
    left: 20px;
    width: calc(100% - 40px);
    max-width: 300px;
  }

  .user-list-scroll {
    top: 40px;
    height: calc(100% - 40px);
    overflow-y: auto;
  }

  .user-avatar-wrapper {
    position: relative;
    display: inline-block;
  }

  .user-avatar {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    margin-right: 10px;
    border: 1px solid #74ffd2;
  }

  .user-name {
    font-weight: 800;
    white-space: nowrap; /* 不换行 */
    overflow: hidden; /* 溢出隐藏 */
    padding-left: 15px;
    text-overflow: ellipsis; /* 超出显示省略号 */
    text-align: left; /* 添加左对齐属性 */
  }

  .user-last-message {
    color: #a19f9f;
    font-size: 14px;
    white-space: nowrap;
    overflow: hidden;
    padding-left: 15px;
    text-overflow: ellipsis;
    text-align: left; /* 添加左对齐属性 */
  }

  .right-side {
    flex: 3;
    display: flex;
    flex-direction: column;
  }

  .chat-header {
    padding: 20px;
    border-bottom: 1px solid #eaeaea;
    font-size: 1.2em;
    color: #37474F;
  }

  .chat-messages {
    flex: 1;
    overflow-y: auto;
    padding: 20px;
  }

  .chat-input {
    padding: 20px;
    display: flex;
    align-items: center;
  }

  .message-input {
    flex: 1;
    margin-right: 10px;
  }

  .send-button {
    flex-shrink: 0;
  }

  .user-item {
    display: flex;
    align-items: center;
    padding: 10px;
    border-bottom: 1px solid #f0f0f2;
  }

  .user-item:hover {
    background-color: #E0E0E0;
    cursor: pointer;
    transition: background-color 0.3s ease;
  }

  .user-details {
    flex-grow: 1; /* 填充剩余空间 */
  }

  .messageBox {
    display: flex;
    align-items: flex-start; /* 将头像和文本第一行对齐 */
    margin-bottom: 10px;
  }

  .messageBox img {
    width: 40px; /* 调整头像大小 */
    height: 40px;
    border-radius: 50%;
    margin-right: 10px;
    margin-left: 10px;
  }

  .messageContent {
    max-width: 70%; /* 调整发送信息宽度 */
    padding: 10px;
    border-radius: 8px;
    background-color: #f0f0f0;
    text-align: left; /* 文本左对齐 */
    word-wrap: break-word; /* 当文本过长时自动换行 */
  }

  .messageTime {
    font-size: 12px;
    color: #999;
    margin-left: 10px;
    margin-top: 5px; /* 将发送时间与文本分隔开 */
  }

  .ownMessage {
    flex-direction: row-reverse;
    align-items: flex-end; /* 将发送时间放置在最下方的贴右位置 */
  }

  .otherMessage {
    flex-direction: row;
    align-items: flex-end; /* 将发送时间放置在最下方的贴左位置 */
  }

  .online-dot {
    position: absolute;
    top: 0;
    left: 0;
    z-index: 1;
    width: 10px;
    height: 10px;
    background-color: #01c201;
    border-radius: 50%;
  }
  .message-badge .el-badge__content {
    position: absolute;
    bottom: 5px; /* Adjust to your desired position */
    left: 5px; /* Adjust to your desired position */
    background-color: #f56c6c; /* Red background for visibility */
    color: white; /* White text color */
  }
</style>

